export const getFileExtension = (fileName:string)=>{
    const dotIndex = fileName.lastIndexOf('.');
    if (dotIndex == -1) {
        return ""; // 如果没有找到点号，返回空字符串或者抛出异常
    }
    return fileName.substring(dotIndex + 1).toLowerCase();
}
export const getFileSize = (file)=>{
    const sizeInKb = Number.isNaN(file)?file.size:file;
    if(!sizeInKb){
        return null;
    }
    if (sizeInKb < 1024) {
        return sizeInKb.toFixed(2) + ' B';
    } else if (sizeInKb < 1024 * 1024) {
        return (sizeInKb / 1024).toFixed(2) + ' KB';
    } else if (sizeInKb < 1024 * 1024 * 1024) {
        return (sizeInKb / (1024 * 1024)).toFixed(2) + ' MB';
    } else if (sizeInKb < 1024 * 1024 * 1024 * 1024) {
        return (sizeInKb / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
    } else {
        return (sizeInKb / (1024 * 1024 * 1024 * 1024)).toFixed(2) + ' TB';
    }
}
export const fileChunk = async (file:File)=>{
    const CHUNK_SIZE = 1024 * 1024 * 5 // 分片大小5M
    const KERNEL_COUNT = navigator.hardwareConcurrency || 4
    return new Promise(((resolve) => {
        // 结果
        let result:any = []
        // 计算分片数量
        let count = Math.ceil(file.size / CHUNK_SIZE)
        // 计算线程开启数量
        let workerCount = Math.ceil(count / KERNEL_COUNT)
        // 当前线程执行完毕的数量
        let finishCount = 0
        for (let i = 0; i < workerCount; i++) {
            // 创建一个线程，并且分配任务
            let worker = new Worker('/public/worker.js', { type: "module" })
            // 开始
            let start = i * KERNEL_COUNT
            // 因为线程数量是向上取整，有除不尽的情况，这里要处理下结束的chunkIndex，如果最后一个chunk大于总chunk数，则写死
            let end = (i + 1) * KERNEL_COUNT
            if (end > count) {
                end = count
            }
            // 分配任务
            worker.postMessage({
                file,
                CHUNK_SIZE,
                startChunkIndex: start,
                endChunkIndex: end
            })
            // 接收处理结果
            worker.onmessage = e => {
                // 这里为了避免顺序乱，取当前的执行索引
                for (let i = start; i < end; i++) {
                    result[i] = e.data[i - start]
                }
                worker.terminate() // 结束任务
                finishCount ++ // 完成数量++
                if (finishCount === workerCount) {
                    resolve(result)
                }
            }
        }
    }))

}


export const blobToBase64 = (blob:Blob)=>{
    return new Promise(resolve => {
        const reader = new FileReader();
        reader.onload = function() {
            const dataUrl = reader.result as string;
            const base64 = dataUrl.split(',')[1];
            resolve(base64);
        };
        reader.readAsDataURL(blob);
    })
}
export const base64ToBlob = (base64:string,type:string)=>{
    const byteCharacters = atob(base64);
    const byteArrays:Uint8Array[] = [];

    for (let offset = 0; offset < byteCharacters.length; offset += 512) {
        const slice = byteCharacters.slice(offset, offset + 512);

        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        const byteArray = new Uint8Array(byteNumbers) as Uint8Array;
        byteArrays.push(byteArray);
    }

    return new Blob(byteArrays, { type: type });
}
export const isPreView =(type:string)=>{
    const obj = {
        'mp4':'mp4'
    }

    return obj[type]
}
export const downloadBlob = (blob:any,fileName:string)=>{
    const link = document.createElement("a");
    link.href = URL.createObjectURL(blob);
    link.download = decodeURI(fileName);
    document.body.appendChild(link);
    link.click();
    window.setTimeout(function() {
        URL.revokeObjectURL(blob);
        document.body.removeChild(link);
    }, 0);
}
